<template>
  <div class="flex">
    <el-button
      size="mini"
      class="button-append m-l-16"
      @click="vote('like')"
      :loading="isLoading.like">
      <svg-icon
        v-show="!isLoading.like"
        :icon-name="likeBtn.icon"
        class="s15"
        style="position: relative; top: 1px;"
      />
      <span>{{ likeBtn.label }}</span>
    </el-button>
    <div class="el-input-group__append flex align-items-center">{{ space.voteCount.like }}</div>
    <el-button
      size="mini"
      class="button-append m-l-16"
      @click="vote('collect')"
      :loading="isLoading.collect"
      :disabled="isSpaceOwner"
      :title="isSpaceOwner ? '不能关注自己的空间' : undefined">
      <svg-icon
        v-show="!isLoading.collect"
        :icon-name="collectBtn.icon"
        class="s15"
        style="position: relative; top: 2px;"
      />
      <span>{{ collectBtn.label }}</span>
    </el-button>
    <div class="el-input-group__append flex align-items-center">{{ space.voteCount.collect }}</div>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import * as spaceFormat from '../format';

export default {
  name: 'VoteButtons', // 空间首页的vote按钮组
  data() {
    return {
      isLoading: {
        like: false,
        collect: false,
      },
    };
  },
  computed: {
    ...mapState(['currentUser']),
    ...mapGetters(['isSpaceOwner']),
    space() { return this.$store.state.currentSpace; },
    likeBtn() {
      if (this.space.voteState.like) return { icon: 'like-fill', label: '已点赞' };
      return { icon: 'like', label: '点赞' };
    },
    collectBtn() {
      if (this.space.voteState.collect) return { icon: 'star-fill', label: '已关注' };
      return { icon: 'star', label: '关注' };
    },
    isOwner() { return this.currentUser.id === this.space.owner.id; },
  },
  methods: {
    ...mapActions(['setCurrentSpace']),
    // 点赞、关注
    vote(action) {
      this.isLoading[action] = true;
      const voteParams = this.initVoteParams(action);
      this.$api.other.vote(voteParams)
        .then((res) => {
          this.voteMessage(action, voteParams.voteState);
          this.setCurrentSpace(spaceFormat.formatSpace(res.data));
          this.$root.$emit('checkScore', this.$va.initScoreType(action, voteParams.voteState));
        })
        .catch(() => {})
        .then(() => { this.isLoading[action] = false; });
    },
    // 点赞、关注所需参数
    initVoteParams(action) {
      return {
        votePosition: this.$C.vote.position.space,
        votePositionId: this.space.id,
        voteAction: this.$C.vote.action[action],
        voteState: !this.space.voteState[action],
      };
    },
    // 点赞、收藏的提醒
    voteMessage(action, voteState) {
      if (voteState) { // 正向操作才有提醒
        if (action === 'like') this.$message.success('点赞成功');
        else if (action === 'collect') this.$message.success('收藏成功');
      }
    },
  },
};
</script>

<style></style>
